package com.updata.up.service;

import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

@Service
public class UpSaveService {

    //计算下载
    public static double sumLen = 0;
    //总大小
//    volatile static int fileSize = 0;
    public static int fileSize = 0;

    /**
     * 保存最新 文件jar包
     *
     * @param uri      地址
     * @param filepath 保存文件路径
     * @return
     * @throws IOException
     */
    public String up(String uri, String filepath, String fileName) throws IOException {
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            //地址url
            URL url = new URL(uri);
            URLConnection conn = url.openConnection();
            inputStream = conn.getInputStream();
            //计算大小
            fileSize = conn.getContentLength();
            System.out.println("文件总共大小：" + fileSize + "字节");

            //获取Content-Disposition名称
 /*       String raw = conn.getHeaderField("Content-Disposition");
//        String fileName = raw.substring(18, 31);
        String fileName = raw;
*/
            System.out.println(fileName);
            File file = new File(filepath + "/test.txt");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //储存位置
            fos = new FileOutputStream(filepath + fileName);

            //进度
            new Thread(() -> {
                while (sumLen < fileSize) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("显示进度:---------" + String.format("%.2f", (sumLen / fileSize) * 100) + "%-----------");
                }
                try {
                    Thread.sleep(3000);
                    sumLen=0;
                    fileSize=0;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();


            int byteread;
            byte[] buffer = new byte[1024];
            while ((byteread = inputStream.read(buffer)) != -1) {
                sumLen += byteread;
                //            System.out.println(sumLen);
                fos.write(buffer, 0, byteread);
            }

            fos.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fos.close();
            inputStream.close();
        }
        return "ok";
    }
}
